package com.ugoodtech.mdcc.web.controller;

/* Copyright (C) Ugoodtech, Inc - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 * Written by Stone Shaw, 15/11/19
 */


import com.ugoodtech.mdcc.core.domain.Photo;
import com.ugoodtech.mdcc.core.service.PhotoService;
import com.ugoodtech.mdcc.core.service.impl.PhotoNotFoundException;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.PhotoResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@ApiIgnore
@Controller
@RequestMapping("/photos")
public class PhotoController {

    @Autowired
    PhotoService photoService;


    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse uploadPhoto(
            @RequestParam(value = "appVersion", required = false) String appVersion,
            @RequestParam(value = "image") MultipartFile image,
            @RequestParam(value = "osType", required = false) String osType,
            @RequestParam(value = "osVersion", required = false) String osVersion
    ) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("--------------uploadPhoto---------------");
            logger.debug("appVersion  = " + appVersion);
            logger.debug("osType  = " + osType);
            logger.debug("osVersion : " + osVersion);

            logger.debug("imageSize  = " + image.getSize());
            logger.debug("imageOriginalFilename  = " + image.getOriginalFilename());
            logger.debug("imageContentType : " + image.getContentType());
        }

        Photo photo = photoService.savePhotoFile(image.getBytes(), image.getOriginalFilename(), null);

        if (null != photo) {
            logger.debug("photoId : " + photo.getId());
            return JsonResponse.successResponseWithData(PhotoResponse.turnPhotoToResponse(photo));
        } else {
            logger.debug("上传照片失败，数据异常");
            logger.debug("--------------------------------------");
            return JsonResponse.errorResponseWithError("上传照片失败，数据异常", "上传照片失败，数据异常");
        }

    }


    @RequestMapping("/getPhoto")
    @ResponseBody
    public void getPhoto(HttpServletResponse response,
                         @RequestParam(value = "photoId") String photoId,
                         @RequestParam(value = "width", required = false) Integer width,
                         @RequestParam(value = "height", required = false) Integer height) throws Exception {


        if (logger.isDebugEnabled()) {
            logger.debug("--------------getPhoto---------------");
            logger.debug("photoId  = " + photoId);
            logger.debug("width  = " + width);
            logger.debug("height  = " + height);
        }


        byte[] bytes;
        try {
            if (null == photoId || "".equals(photoId) || "null".equals(photoId) || "undefined".equals(photoId)) {
                bytes = photoService.getDefaultPhoto("atongmu.jpg");
            } else if (null != width && 0 != width && null != height && 0 != height) {
                bytes = photoService.getPhotoThumbnailBytes(Long.parseLong(photoId), width, height);

            } else {
                bytes = photoService.getPhotoBytes(Long.parseLong(photoId));
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("获取图片异常");
            throw new Exception("获取图片异常");
        } catch (PhotoNotFoundException e) {
            e.printStackTrace();
            logger.debug("图片不存在");
            throw new Exception("图片不存在");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.debug("获取图片参数异常");
            throw new Exception("获取图片参数异常");
        }
        String extensionName = "jpg";
        response.setContentType("image/" + extensionName);
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
    }


    Logger logger = LoggerFactory.getLogger(PhotoController.class);
}
